const app = getApp();
const {AskPage} = app._require('common/index');
const formMixin = app._require("mixins/form.mixin.js").default;
const {taskMixin} = app._require("pages/task/mixin.js");
const {AskComponent} = app._require("common/index");

const share = app._require("pages/task-share-form/handleShare").default;
AskPage({
    /**
     * 页面的初始数据
     */
    name: "home",
    mixins: [formMixin, taskMixin],
    data: {
        navBarHeight: app.globalData.navBarHeight,//导航栏高度
        showStatusBox: false,
        showOnFillPop: false,
        orgCategoryId: app.user.userInfo.orgCategoryId,
        statusBoxItems: [],
        share: {
            show: false,
            item: null,
            list: [
                {name: "转发给其他人填报", value: "orgOut", openType: "share", taskId: ""},],
        },
        noticeList: [],
        taskTypeValue: "past",
        taskTypeList: [
            {label: "进行中", value: "past", state: "1"},
            {label: "已完成", value: "expiring", state: "2"},
            {label: "全部", value: "all", state: "0"},
        ],
        triggered: false
    },
    onLoad: function (options) {
        this.setData({
            triggered: true
        });
    },
    checkShowAlert() {
        if (app.user.token.length > 0) {
            //判断一下
            let openId = app.user.userInfo.openId;
            let showAlert = app.user.userInfo.showAlert;
            var that = this;
            if (openId.length == 0 && showAlert == true) {
                // 绑定
                app.user.userInfo.showAlert = false;
                wx.showModal({
                    title: '微信绑定提醒',
                    content: '你还没有绑定微信，绑定微信后可接收微信消息提醒。',
                    cancelText: "绑定微信",//默认是“取消”
                    confirmText: "下次绑定",
                    success: function (res) {
                        if (res.confirm) {
                        } else if (res.cancel) {
                            that.bindWxAction();
                        }
                    }
                })
            }
        }
    },
    onShow() {
        if (typeof this.getTabBar === "function" && this.getTabBar()) {
            this.getTabBar().setData({
                active: "/" + this.route,
            });
        }
        // let _change = app.user.clearTask;
        // if (_change == true) {
        this.loginSuccess();
        this.loginFail();
        app.user.clearTask = false;
        wx.setStorage({
            key: "user",
            data: app.user
        });
        // }
        this.setData({
            user: app.user,
        });
        if (app.user.token.length > 0) {
            // this.checkShowAlert();
        } else {
            this.loginFail();
        }
    },
    onRefresh() {
        if (this._freshing) return
        this._freshing = true
        setTimeout(() => {
            this.onPullDownRefresh();
            this.setData({
                triggered: false
            })
            this._freshing = false
        }, 500)
    },
    onShareAppMessage(e) {
        let task = this.selectComponent("#taskList");
        let {item} = task.data.share;
        item = item || {};
        let {userInfo} = this.data.user;
        let path = share.handleForm(
            {
                taskId: item.id || "",
                isCms: item.isCms ? "1" : "0",
                shareId: userInfo.id || "",
                sharePhone: this.data.user.phone || "",
            },
            ""
        );
        return {
            title: item.name,
            path: path,
            imageUrl: "/assets/logo.png",
        };
    },
    handleTabClick(e) {
        let {name} = e.detail;
        this.setData({
            taskTypeValue: name,
        });
        this.initData();
    },
    getInitParams() {
        let status = this.$key2Name({
            type: this.data.taskTypeValue + "",
            name: "state",
            list: this.data.taskTypeList,
        });
        return {
            url: "task/list",
            data: {
                status,
                //全部为0，我创建的为1，我收到的为2
                taskKind: (status == 0 ? 0 : 2),
            },
        };
    },
    loginSuccess() {
        this.initData();
    },
    zfAction(e) {
        let item = e.detail.data;
        console.log(item);
        this.setData({
            "currentItem": item
        })
        this.onShare(item);
    },

    onShareAppMessage: function (e) {//点击button分享按钮触发此分享事件
        let item = this.data.currentItem;
        const userInfo = (app.user && app.user.userInfo) || {};
        console.log(item)
        return {
            title: '表单填报：' + item.source.formName,
            path: "/pages/home/collection/collection-details/index?formId=" + item.source.formId + "&dataCount=" + item.source.dataCount + "&type=share" + "&userId=" + userInfo.id + "&processInstanceId=" + item.source.processInstanceId + "&taskId=" + item.source.id + "&cityCode=" + userInfo.cityCode + "&departmentId=" + userInfo.departmentId + "&governmentId=" + userInfo.governmentId + "&orgCategoryId=" + userInfo.orgCategoryId,
            success: function (res) {
                // 转发成功
                wx.showToast({
                    title: "分享成功",
                    icon: 'success',
                    duration: 2000
                })
            },
            fail: function (res) {
                // 分享失败
                wx.showToast({
                    title: "分享失败",
                    icon: 'success',
                    duration: 2000
                })
            },
        }
    },
    //分享
    onShare(e) {
        let item = e;
        let auth = this.checkAuth();
        if (!auth) return;
        this.data.share.item = item;
        this.setData({
            "share.show": true,
        });
    },
    onShareClose() {
        this.setData({
            "share.show": false,
        });
    },
    onfillAction(e) {
        let item = e.detail;
        console.log(item);
        this.setData({
            "showOnFillPop": true,
            "currentItem": item
        })
    },
    reloadData(e) {
        this.initData();
    },
    scrollReachBottom() {
        this._scrollReachBottom();
    },
    submitAction() {
        let item = this.data.currentItem;
        this.onEnd(item);
        this.setData({
            "showOnFillPop": false
        })
    },
    async onEnd(e) {
        let auth = this.checkAuth();
        if (!auth) return;
        let info = {
            msg: "任务已完成",
            errMsg: "状态修改失败"
        }
        try {
            let nowItem = e.item;
            const response = await this.$_server("task/finish", {
                data: {
                    taskId: nowItem.id
                },
            });
            let {data} = response;
            console.log(data);
            if (data.code !== 200) {
                wx.showToast({
                    title: data.message,
                    icon: "none"
                })
                throw data;
            }
            let tableData = this.data.tableData;
            let index = e.index;
            let item = nowItem;
            // console.log(index);
            // console.log(item);
            let bageInfo = this.data.bageInfo;
            //成功后移除
            tableData.splice(index, 1);
            let doingValue = bageInfo["1"];
            console.log(bageInfo);
            try {
                doingValue = parseInt(doingValue);
                doingValue--;
                bageInfo["1"] = doingValue <= 0 ? "" : doingValue;
            } catch (e) {
            }
            ;
            this.setData({
                "tableData": tableData,
                "bageInfo": bageInfo
            })
        } catch (error) {
            if (error.message) {
                wx.showToast({
                    mask: true,
                    title: error.message || info.errMsg,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    loginSuccess(e) {
        console.log(app.user);
        this.onRefresh();
        this.checkShowAlert();
        this.setData({
            "user": app.user
        })
    },
    reloadToatalAction() {
        this.reloadToatal()
    },
    reloadToatal() {
        try {
            let newTableData = this.data.tableData;
            this.initData()
            this.setData({
                tableData: newTableData
            })
        } catch (e) {
            console.log(e)
        }
    }
});
